package com.springboot.system.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.springboot.system.domain.auth.Role;
import com.springboot.system.domain.auth.RoleVO;
import com.springboot.common.utils.StringUtils;
import com.springboot.core.jdbc.BaseDao;
import com.springboot.core.web.mvc.Page;

/**
 * 角色数据持久层实现类
 * 
 * @ClassName: RoleDao
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 252956
 * @date 2021年1月7日 上午9:40:36
 *
 */
@Repository
public class RoleDao extends BaseDao {

	public Page<Role> selectPage(RoleVO role) {
		List<Role> list = super.select(
				getSqlPageHandle().handlerPagingSQL(rolePageSql(role, 0), role.getPage(), role.getLimit()), null,
				Role.class);
		int count = super.getJdbcTemplate().queryForObject(rolePageSql(role, 1), null, Integer.class);
		Page<Role> page = new Page<Role>(list, count, role.getLimit(), role.getPage());
		return page;
	}

	private String rolePageSql(RoleVO role, int type) {
		StringBuilder sql = new StringBuilder();
		if (type == 0) {
			sql.append("select * from t_sys_role");
		} else {
			sql.append("select count(*) from t_sys_role");
		}
		sql.append(" where 1=1");

		if (StringUtils.isNotBlank(role.getName())) {
			sql.append(" and name like '%").append(role.getName().trim() + "%' ");
		}
		if (type == 0) {
			if (StringUtils.isNotBlank(role.getSidx())) {
				if ((role.getSord().trim().equalsIgnoreCase("asc"))) {
					sql.append(" order by " + role.getSidx().split(" ")[0] + " asc");
				} else {
					sql.append(" order by " + role.getSidx().split(" ")[0] + " desc");
				}
			} else {
				sql.append(" order by id asc");
			}
		}
		return sql.toString();
	}

	public List<Role> selectByUser(String userId) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				"SELECT r.id,r.name,r.data_scope from t_sys_user_role ur INNER JOIN t_sys_role r on ur.role_id=r.id ");
		sql.append(" where r.status=1 and  ur.user_id=? ");

		return super.select(sql.toString(), new Object[] { userId }, Role.class);
	}

	public List<Integer> selectRoleDetp(Integer roleId) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT dept_id from  t_sys_role_dept  ");
		sql.append(" where  role_id=" + roleId + " ");
		return super.getJdbcTemplate().queryForList(sql.toString(), Integer.class);
	}

	public int updateStatus(String id, Integer status) {
		StringBuilder sql = new StringBuilder();
		sql.append("update t_sys_role set status=? where id=?");
		return super.insertOrUpdateOrDelete(sql.toString(), new Object[] { status, id });
	}
}
